package com.duoec.magichour.core.web;

import com.duoec.magichour.core.exceptions.BusinessException;
import com.duoec.magichour.dto.BaseResponse;
import com.duoec.magichour.dto.UserInfo;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ycoe on 17/6/25.
 */
public class BaseWebController {
    protected UserInfo getUserInfo() {
        return UserInfoHolder.get();
    }
    private static final ThreadLocal<MyModelAndView> VIEW = new ThreadLocal<>();

    public void addData(String name, Object value) {
        VIEW.get().addData(name, value);
    }


    @ExceptionHandler({BusinessException.class})
    public ModelAndView handleException(BusinessException e) {
        if(e.getCode() == BaseResponse.CODE_FORBID) {
            //权限不足
            if(getUserInfo() == null) {
                return redirect("/login.html");
            }
        }
        addData("error", e);

        //打开错误页面
        return view("/error.ftl");
    }

    protected ModelAndView view(String viewName) {
        MyModelAndView view = VIEW.get();
        view.addAllObjects(view.getModelData());
        view.setViewName(viewName);
        return view;
    }

    protected Object getData(String key) {
        return VIEW.get().getModelData().get(key);
    }

    /**
     * 302跳转
     *
     * @param url 跳转的URL,可以是相对链接
     * @return
     */
    protected ModelAndView redirect(String url) {
        this.VIEW.get().clear();
        this.VIEW.get().setViewName("redirect:" + url);
        return this.VIEW.get();
    }

    /**
     * 301跳转
     *
     * @param url
     * @return
     */
    public ModelAndView redirect301(String url) {
        RedirectView red = new RedirectView(url, true);
        red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        return new ModelAndView(red);
    }

    public void setView(MyModelAndView view) {
        this.VIEW.set(view);
    }

    /**
     * 每个请求进来后会首先请求此方法!
     *
     * @param request
     * @param response
     */
    public void preHandle(HttpServletRequest request, HttpServletResponse response) {
        //给子类重写
    }

    protected String getDomain() {
        return (String) getData("domain");
    }
}
